package com.chenjj.bankm.example.provider.ctrl;

import com.chenjj.bankm.example.provider.property.ApplicationProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class SimpleRestController {

    @Autowired
    ApplicationProperties applicationProperties;

    @GetMapping("/getUser")
    @HystrixCommand(fallbackMethod = "getUserFallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
    })
    @ResponseBody
    public Map<String,Object> getUser(@RequestParam Integer id) throws InterruptedException {

        //模拟熔断
        Random random = new Random();
        Thread.sleep(random.nextInt(2000));


        System.out.println("provider-example getUser executed!");
        Map<String,Object> data = new HashMap<>();
        data.put("id",id);
        data.put("userName","admin");
        data.put("from","provider-example");
        data.put("config.info",applicationProperties.getConfigInfo());
        return data;
    }

    public Map<String,Object> getUserFallback(Integer id){
        System.out.println("provider-example getUserFallback executed!");
        Map<String,Object> data = new HashMap<>();
        data.put("info","getUserFallbackExecuted");
        return data;
    }
}
